package com.wy.panda.common.property.converter;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Set;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import com.wy.panda.common.property.annotation.ConvertMethod;
import com.wy.panda.exception.PandaCannotHandleException;

/**
 * 依据某object值转换成枚举类型
 * 
 * @author wangyuan
 * @since 2020-9-20 22:33:21
 *
 */
public class ObjectToEnumConverter implements ConditionalGenericConverter {

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return null;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        Class<?> targetClass = targetType.getType();
        
        Method[] methods = targetClass.getMethods();
        
        Method method = null;
        for(Method methodItem : methods) {
            if(null != methodItem.getAnnotation(ConvertMethod.class)) {
                method = methodItem;
                break;
            }
        }
        
        if(null == method) {
            return source;
        }
        
        Type[] parameterTypes = method.getParameterTypes();
        Class<?> parameterClass = (Class<?>) parameterTypes[0];
        
        Object parameterVal = null;
        Object result = null;
        try {
            if(Integer.class.equals(parameterClass)) {
                if(Integer.class.equals(sourceType.getType())) {
                    parameterVal = (Integer) source;
                } else if(String.class.equals(sourceType.getType())) {
                    parameterVal = Integer.valueOf((String) source);
                } else {
                    //不能处理的类型
                    throw new UnsupportedOperationException("不能处理的类型：" + sourceType.getType());
                }
            } else if(String.class.equals(parameterClass)) {
                parameterVal = (String) source;
            } else {
                //不能处理的类型
                throw new UnsupportedOperationException("不能处理的类型：" + sourceType.getType());
            }
            
            result = method.invoke(null, parameterVal);
        } catch (Exception e) {
            throw new PandaCannotHandleException("属性注入错误：", e);
        }
        
        return result;
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        if(sourceType.getType().isEnum()) {
            return false;
        }
        
        if(targetType.getType().isEnum()) {
            return true;
        }
        
        return false;
    }

}
